package com.xb.loan.cashier.biz.service.impl;

import com.xb.loan.cashier.biz.dao.bean.CashierEncashOrder;
import com.xb.loan.cashier.biz.dao.bean.CashierPayChannel;
import com.xb.loan.cashier.biz.dao.bean.CashierPayChannelBank;
import com.xb.loan.cashier.biz.pay.alipay.AlipayPayment;
import com.xb.loan.cashier.biz.service.CashierEncashOrderService;
import com.xb.loan.cashier.biz.service.CashierPayChannelBankService;
import com.xb.loan.cashier.biz.service.CashierPayChannelService;
import com.xb.loan.cashier.biz.util.Configure;
import com.xb.loan.cashier.service.IEncashOrderService;
import com.xb.loan.cashier.service.bean.CashierEncashBO;
import com.xb.loan.cashier.service.bean.CashierPayChannelBankBO;
import com.xb.loan.cashier.service.constant.ICashierEnumConst;
import com.xb.loan.cashier.service.exception.ICashierServiceException;
import com.xb.loan.log.exception.BizException;
import com.xb.loan.util.StringUtils;
import com.xb.loan.util.cache.redis.comm.FormatOperation;
import com.xb.loan.util.common.ObjectOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 提现业务逻辑实现层
 */
@Service("encashOrderService")
public class EncashOrderServiceImpl implements IEncashOrderService {
	
	private static Logger log = LoggerFactory.getLogger(EncashOrderServiceImpl.class);
	
	 @Autowired
	 private CashierEncashOrderService cashierEncashOrderService;
	 
	 @Autowired
	 private CashierPayChannelBankService cashierPayChannelBankService;
	 
	 @Autowired
	 private CashierPayChannelService cashierPayChannelService;

	@Override
	public void encash(CashierEncashBO encashBO) throws BizException {
		log.info("encash 接收到参数：" + encashBO.toString());
        String userId = encashBO.getUserId();
        String orderId = encashBO.getOrderId();
        String platId = encashBO.getPlatId();
        String partnerId = encashBO.getPartnerId();
        String loginName = encashBO.getLoginName();
        double money = encashBO.getMoney();
        String accountPeriod = encashBO.getAccountPeriod();
        String sellName = encashBO.getSellName();
        String sellAccount = encashBO.getSellAccount();
        String sellBank = encashBO.getSellBank();
        String sellBankBranch = encashBO.getSellBankBranch();
        String sellProvince = encashBO.getSellProvince();
        String sellCity = encashBO.getSellCity();
        String sign = encashBO.getSign();
        
        // 验证参数
        if(StringUtils.isBlank(userId)||StringUtils.isBlank(orderId)||StringUtils.isBlank(platId)
                || StringUtils.isBlank(partnerId) || StringUtils.isBlank(accountPeriod) || StringUtils.isBlank(sellName)
                || StringUtils.isBlank(sellAccount) || StringUtils.isBlank(sellBank) || StringUtils.isBlank(sign)
                || money<=0){
        	log.warn("提现输入参数有误！" + encashBO.toString());
            throw ICashierServiceException.inputParameterIsWrong;
        }
        
        // 记录存在直接返回成功
        CashierEncashOrder temp = cashierEncashOrderService.selectByOrderId(encashBO.getOrderId());
        if(temp!=null){
        	log.warn("提现订单已存在，订单号为：" + encashBO.getOrderId());
            return;
        }
        // 插入记录
        CashierEncashOrder order = new CashierEncashOrder();
        order.setAccountDayPlat(accountPeriod);
        order.setSellBankBranch(sellBankBranch);
        order.setCreateTime(new Date());
        order.setLoginName(loginName);
        order.setMoney(money);
        order.setOrderId(orderId);
        order.setPartnerId(partnerId);
        order.setPlatId(platId);
        order.setSellAccount(sellAccount);
        order.setSellBank(sellBank);
        order.setSellCity(sellCity);
        order.setSellName(sellName);
        order.setSellProvince(sellProvince);
        order.setUserId(userId);
        order.setSign(sign);
        // 验签
        if(!cashierEncashOrderService.validateEncashSign(order)){
        	log.warn("提现订单验签失败：" + order);
            throw ICashierServiceException.VALIDATE_ERROR;
        }
        
        order.setAccountStatus(ICashierEnumConst.CashierAccountStatus.INIT.getStatus());
        order.setPushStatus(ICashierEnumConst.CashierEncashSendStatus.NOTSEND.getStatus());
        order.setCashierOrderId(FormatOperation.assemblySeq("encashOrder", 4, FormatOperation.formatDateToYMDHms(new Date()), ""));
        order.setStatus(ICashierEnumConst.CashierEncashStatus.WAIT.getStatus());
        log.warn("插入提现订单：" + order);
        cashierEncashOrderService.insert(order);
        log.info("encash 处理结束");
	}

	@Override
	public List<CashierPayChannelBankBO> queryPayChannelBanksByPage(Integer pageNum,
                                                                    Integer pageSize, String bankCode) {
		
		List<CashierPayChannelBank> list = cashierPayChannelBankService.queryPayChannelBanksByPage(pageNum, pageSize, bankCode);
		List<CashierPayChannelBankBO> results = ObjectOperation.convertByClassesList(list, CashierPayChannelBankBO.class);
		return results;
	}

	@Override
	public String queryBankNameByCode(String bankCode) {
		return cashierPayChannelBankService.queryBankNameByCode(bankCode);
	}

	@Override
	public void alipayEncashNotifyDeal(Map<String, String> alipayParams,
		String payChannelId) throws BizException {
		log.info("alipayEncashNotifyDeal 接收到参数:"+alipayParams.toString());
		String notifyType = alipayParams.get("notify_type");
		if (AlipayPayment.BPTB_UNFREEZE_NOTIFY.equals(notifyType)) {
			throw ICashierServiceException.ALIPAY_UNFREEZE_LACK;
		}
		String sign_type=alipayParams.get("sign_type");
        String file_name=alipayParams.get("file_name");
        CashierPayChannel payChannel = cashierPayChannelService.selectByPayChannelId(payChannelId);
        if(payChannel==null){
            throw ICashierServiceException.PAY_CHANNEL_NOT_EXIST;
        }
        String sign_key = ICashierEnumConst.CashierEncryptType.MD5.getDesc().equals(sign_type)?payChannel.getMd5Key():payChannel.getPublicKey();
        String partner = payChannel.getChannelUser();
        String payUrl = payChannel.getPayUrl();
        boolean verify_result = AlipayPayment.notify_verify(alipayParams, partner, sign_type, sign_key, payUrl);
        if(!verify_result){
            throw ICashierServiceException.VALIDATE_ERROR;
        }
        // 下载结果文件
        String resultFilePath = Configure.getStringValue("task.encashresult.alipay.file.path");
        try {
			boolean isSuccess = AlipayPayment.bptb_result_file(file_name,
					resultFilePath, partner, sign_type, sign_key, payUrl);
			if (!isSuccess) {
				throw ICashierServiceException.DOWN_ENCASH_RESULT_FAIL;
			}
			// 处理提现结果
			cashierEncashOrderService.updateEncashResultFile(resultFilePath, file_name);
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}
	}
	
}
